<template>
  <div>
    <h2>文件上传</h2>
    <!--
    :http-request="uploadFile"  是用来覆盖默认的action的请求路径的
    action=""不能删除,因为是<el-upload>组件必填参数,不填会报错
    -->
    <el-upload
      class="upload-demo"
      drag
      action=""
      :http-request="uploadFile"
      :on-change="handleChange"
      multiple>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>

    <div>
      <!-- 上传后展现图片的地方 -->
      <img :src="fileSrc" width="200px">
    </div>
<!--    数据展示区-->
    <el-table :data="tableData">
      <el-table-column prop="id" label="ID" width="180"></el-table-column>
      <el-table-column label="文件">
        <template #default="scope">
          <el-image
            :src="scope.row.fileName"        style="width: 120px; height: 80px"
            :preview-src-list="[scope.row.fileName]"
            fit="contain">
            <template #error>
              <div class="image-error">
                <i class="el-icon-picture-outline"></i>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
    </el-table>

  </div>
</template>

<script>
import {list, uploadPicture} from '@/api/upload'
export default {
  name:"upload",
  data(){
    return{
      file:null,
      fileSrc:null,
      tableData:[]
    }
  },
  created() {
    this.findAllFile()
  },
  methods:{
    handleChange(file){
      this.file = file.raw;

    },
    uploadFile(){
      const file = this.file;
      // FormData是js对象,用于存储表单数据
      const formData = new FormData();
      formData.append("file", file); // 由后端接口决定,后端参数叫file
      uploadPicture(formData).then((res) => {
        this.$message({
          message: "上传成功",
          type: "success",
        });
        this.fileSrc = res.data
        console.log("fileSrc",this.fileSrc)
      });
    },
    findAllFile(){
      list().then((res) => {
        this.tableData = res.data.map(item => ({
          ...item,
          fileName: `https://jinghaiyang.oss-cn-beijing.aliyuncs.com/app/upload/${item.fileName}`
        }))
        console.log("tableData",this.tableData)
        console.log(this.tableData[0].fileName)
      })
    }
  }
}
</script>


<style scoped lang="scss">

</style>
